/****************************************************************************
 *  QLyrics - A simple lyrics viewer.                                       *
 *  Copyright (C) 2008  hsys <hanshuiys@gmail.com>                          *
 *                                                                          *
 *  This program is free software; you can redistribute it and/or modify    *
 *  it under the terms of the GNU General Public License as published by    *
 *  the Free Software Foundation; either version 3 of the License, or       *
 *  (at your option) any later version.                                     *
 *                                                                          *
 *  This program is distributed in the hope that it will be useful,         *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of          *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           *
 *  GNU General Public License for more details.                            *
 *                                                                          *
 *  You should have received a copy of the GNU General Public License       *
 *  along with this program; if not, write to the Free Software Foundation, *
 *  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA       *
 ****************************************************************************/

#include "lyricsbaiduprovider.h"
#include <QBuffer>
#include <QUrl>
#include <QHttp>
#include <QTextCodec>

LyricsProvider* LyricsBaiduProvider::Builder::create(const Track& track, QObject* parent) const {
    LyricsBaiduProvider* inst = new LyricsBaiduProvider(parent);
    inst->m_track = track;
    return inst;
};

const QString& LyricsBaiduProvider::Builder::getProviderName() const {
    static QString name = LyricsBaiduProvider::tr("Baidu search");
    return name;
};

LyricsBaiduProvider::LyricsBaiduProvider(QObject* parent) : LyricsProvider(parent) {
    m_buffer = NULL;
};

void LyricsBaiduProvider::search() {
    if (m_buffer != NULL)
        delete m_buffer;
    m_buffer = new QBuffer(this);

    QTextCodec* codec = QTextCodec::codecForName("GBK");
    QString searchUrl = "/s?wd=filetype%3Alrc+"
            + encodeUrlQuery(codec->fromUnicode(m_track.artist + " " + m_track.title));

    m_http = new QHttp(this);
    m_http->setHost("www.baidu.com", QHttp::ConnectionModeHttp, 80);
    connect(m_http, SIGNAL(done(bool)), SLOT(slotSearchDone(bool)));

    // save the http request id for further use
    m_http->get(searchUrl, m_buffer);
};

void LyricsBaiduProvider::slotSearchDone(bool error) {
    m_http->deleteLater();
    m_http = NULL;
    if (error) {
        m_status = NetworkError;
    } else {
        parseResult();
    };
    emit signalSearched();

    //m_http->deleteLater();
    //m_http = NULL;
};

void LyricsBaiduProvider::parseResult() {
    QTextCodec* codec = QTextCodec::codecForName("GBK");
    QString content = codec->toUnicode(m_buffer->data());

    m_status = NotFound;
    if (content.contains("noresult")) {
        return;
    };
    
    //cut head & tail
    bool ok = true;
    int pos;
    pos = content.indexOf("ScriptDiv");
    if (pos == -1)
        ok = false;
    content = content.mid(pos);
    pos = content.indexOf("background-color:#EFF2FA;height:60px;width:100%;clear:both");
    if (pos == -1)
        ok = false;
    content = content.left(pos);
    if (!ok) {
        m_status = NetworkError;
        return;
    };

    // remove all highlight tag
    content.replace(QRegExp("<font color=#C60A00>([^<]*)</font>"), "\\1");
    // part all result
    QStringList part = content.split("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">", QString::SkipEmptyParts);
    SearchResult r;
    for (int i = 1; i < part.size(); ++i) {
        // substract title and artist
        r.title = part.at(i).section("<font size=\"3\">", 1).section("</font>", 0, 0).trimmed();
        r.artist = r.title.section(" - ", 1).trimmed();
        r.title = r.title.section(" - ", 0, 0).trimmed();
        if (r.title.isEmpty() || r.artist.isEmpty())
            continue;

        r.album.clear();
        r.url = part.at(i).section("<a onclick=", 1, 1).section("target=\"_blank\"", 0, 0)
                .section("href=\"", 1, 1).section("\"", 0, 0).trimmed();

        r.preview = part.at(i).section("HTML", 2, 2).section("<br>", 1, 1).trimmed();
        if (!r.url.isEmpty())
            m_result.push_back(r);
    };
};
